<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="标题" prop="title">
              <el-input v-model="queryParams.title" placeholder="请输入标题" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="发文单位" prop="releaseUnit">
              <el-input v-model="queryParams.releaseUnit" placeholder="请输入发文单位" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="是否置顶" prop="hasTop">
              <el-select v-model="queryParams.hasTop" placeholder="请选择是否置顶" clearable>
                <el-option v-for="dict in ywsf" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否轮播" prop="hasCarousel">
              <el-select v-model="queryParams.hasCarousel" placeholder="请选择是否轮播" clearable>
                <el-option v-for="dict in ywsf" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="发布时间" style="width: 308px">
              <el-date-picker
                v-model="dateRangeReleaseTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:noticeNews:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:noticeNews:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:noticeNews:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:noticeNews:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:noticeNews:audit']" type="success" plain icon="Help" :disabled="multiple" @click="handlePass"
              >批量审核</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:noticeNews:visible']" type="primary" plain icon="Document" :disabled="multiple" @click="handleShow"
              >批量展示</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['business:noticeNews:doCarousel']" type="warning" plain icon="Picture" :disabled="multiple" @click="handlePic"
              >批量轮播</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="noticeNewsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="主键" align="center" prop="baseId" />
        <el-table-column show-overflow-tooltip width="355" label="标题" align="center" prop="title" />
        <el-table-column label="封面" align="center" prop="coverImage" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.coverImageUrl" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sort" />
        <el-table-column label="是否置顶" align="center" prop="hasTop">
          <template #default="scope">
            <el-switch
              v-model="scope.row.hasTop"
              :active-value="1"
              :inactive-value="0"
              inline-prompt
              :active-icon="Check"
              :inactive-icon="Close"
              @change="switchChange($event, scope.row, 'hasTop')"
            />
          </template>
        </el-table-column>
        <el-table-column label="是否轮播" align="center" prop="hasCarousel">
          <template #default="scope">
            <el-switch
              v-model="scope.row.hasCarousel"
              :active-value="1"
              :inactive-value="0"
              inline-prompt
              :active-icon="Check"
              :inactive-icon="Close"
              @change="switchChange1($event, scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="对外展示" align="center" prop="visible">
          <template #default="scope">
            <el-switch
              v-model="scope.row.visible"
              :active-value="1"
              :inactive-value="0"
              inline-prompt
              :active-icon="Check"
              :inactive-icon="Close"
              @change="switchChange2($event, scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="发布时间" align="center" prop="releaseTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.releaseTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="浏览量" align="center" prop="viewCount" />
        <el-table-column label="审核状态" align="center" width="100">
          <template #default="scope">
            <el-popover v-if="scope.row.status == 2" placement="top-start" :width="200" effect="dark" trigger="hover" :content="scope.row.reason">
              <template #reference>
                <el-tag type="danger">审核驳回</el-tag>
              </template>
            </el-popover>
            <el-tag v-else-if="scope.row.status == 0" type="success">审核通过</el-tag>
            <el-tag v-else-if="scope.row.status == 1" type="warning">待审核</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['business:noticeNews:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['business:noticeNews:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status == 1" content="审核" placement="top">
              <el-button v-hasPermi="['business:noticeNews:audit']" link type="primary" icon="Help" @click="handleAudit(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 审核对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" :z-index="1002">
      <el-form ref="noticeNewsFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="审核状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="true">审核通过</el-radio>
            <el-radio :label="false">审核驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :rules="{ required: !form.status, message: '驳回原因不能为空', trigger: 'blur' }"
          v-show="form.status == false"
          label="驳回原因"
          prop="reason"
        >
          <el-input :rows="6" type="textarea" show-word-limit maxlength="100" v-model="form.reason" placeholder="请输入驳回原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="NoticeNews" lang="ts">
import { listNoticeNews, delNoticeNews, addNoticeNews, updateNoticeNews, auditChange, visibleChange, doCarousel } from '@/api/business/noticeNews';
import { NoticeNewsVO, NoticeNewsQuery } from '@/api/business/noticeNews/types';
import { AuditForm } from '@/api/business/notice/types';
import { Check, Close } from '@element-plus/icons-vue';
import router from '@/router';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { ywsf } = toRefs<any>(proxy?.useDict('ywsf'));
const route = useRoute();
const noticeNewsList = ref<NoticeNewsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeReleaseTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const noticeNewsFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: AuditForm = {
  baseIds: undefined,
  status: undefined,
  reason: undefined
};
const data = reactive<PageData<AuditForm, NoticeNewsQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: undefined,
    releaseUnit: undefined,
    hasTop: undefined,
    hasCarousel: undefined,
    visible: undefined,
    params: {
      releaseTime: undefined
    }
  },
  rules: {
    status: [{ required: true, message: '审核状态不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询检察要闻列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeReleaseTime.value, 'ReleaseTime');
  const res = await listNoticeNews(queryParams.value);
  noticeNewsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};
//是否置顶
const switchChange = async (checked: boolean, row: NoticeNewsVO, name: string) => {
  row[name] = checked;
  await updateNoticeNews(row);
  getList();
};
//是否轮播
const switchChange1 = async (checked: boolean, row: NoticeNewsVO) => {
  await doCarousel([row.baseId], checked);
  await getList();
};
//是否展示
const switchChange2 = async (checked: boolean, row: NoticeNewsVO) => {
  await visibleChange([row.baseId], checked);
  await getList();
};
/** 批量审核通过 */
const handlePass = async () => {
  await proxy?.$modal.confirm('是否确认批量审核通过选中数据？').finally(() => (loading.value = false));
  await auditChange(ids.value, true, '');
  proxy?.$modal.msgSuccess('操作成功');
  await getList();
};
/** 批量展示 */
const handleShow = async () => {
  await proxy?.$modal.confirm('是否确认批量展示选中数据？').finally(() => (loading.value = false));
  await visibleChange(ids.value, true);
  proxy?.$modal.msgSuccess('操作成功');
  await getList();
};
/** 批量轮播 */
const handlePic = async () => {
  await proxy?.$modal.confirm('是否确认批量轮播选中数据？').finally(() => (loading.value = false));
  await doCarousel(ids.value, true);
  proxy?.$modal.msgSuccess('操作成功');
  await getList();
};
/** 单个审核 */
const handleAudit = (row?: NoticeNewsVO) => {
  reset();
  form.value.baseIds = [row.baseId];
  dialog.title = '审核';
  dialog.visible = true;
};
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  noticeNewsFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeReleaseTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: NoticeNewsVO[]) => {
  ids.value = selection.map((item) => item.baseId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  router.push({ path: '/noticeNew/addNoticeNews', query: { type: route.query.type } });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: NoticeVO) => {
  router.push({
    path: '/noticeNew/addNoticeNews',
    query: {
      id: row?.baseId || ids.value[0],
      type: route.query.type
    }
  });
};
/** 提交按钮 */
const submitForm = () => {
  noticeNewsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await auditChange(form.value.baseIds, form.value.status, form.value.reason).finally(() => (buttonLoading.value = false));
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: NoticeNewsVO) => {
  const _baseIds = row?.baseId || ids.value;
  await proxy?.$modal.confirm('是否确认删除检察要闻编号为"' + _baseIds + '"的数据项？').finally(() => (loading.value = false));
  await delNoticeNews(_baseIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/noticeNews/export',
    {
      ...queryParams.value
    },
    `noticeNews_${new Date().getTime()}.xlsx`
  );
};

onActivated(() => {
  getList();
});
</script>
